package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.constants.wemedia.WemediaConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsDTO;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String webSite;

    @Resource
    WmNewsMaterialMapper wmNewsMaterialMapper;

    @Resource
    WmMaterialMapper wmMaterialMapper;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Resource
    WmNewsMapper wmNewsMapper;

    @Resource
    WmUserMapper wmUserMapper;

    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        //参数检查
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件封装执行查询
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        //文章标题模糊查询
        wrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        //频道id
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        //文章状态
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        //发布时间 >= 开始时间
        wrapper.ge(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate()).
                le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        //按照用户id查询
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        // 按照创建日期倒序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        // 分页条件构建
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //执行查询
        IPage<WmNews> pageResult = this.page(page, wrapper);
        //4 返回封装查询结果
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        //处理文章图片
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult delNews(Integer id) {
        //1.检查参数
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
//● 当前已经发布（状态为9）的文章可以上架（enable = 1），也可以下架（enable = 0）
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable == null ||
                (!WemediaConstants.WM_NEWS_UP.equals(enable) && !WemediaConstants.WM_NEWS_DOWN.equals(enable))) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "上下架状态错误");
        }
        //查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //判断文章是否发布
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "不是发布状态");
        }
        //4.修改文章状态，同步到app端（后期做）TODO
        this.update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId, dto.getId()).set(WmNews::getEnable, dto.getEnable()));



        //5. 上下架发送消息通知  用于同步article 及 elasticsearch
        if(wmNews.getArticleId()!=null){
            if (enable.equals(WemediaConstants.WM_NEWS_UP)){
                //上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }

        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
//        检测参数
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = this.getById(id);
        if (wmNews == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if (wmNews.getUserId() != null) {
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }
        //4.封装vo信息返回
        WmNewsVO wmNewsVO = new WmNewsVO();
        BeanUtils.copyProperties(wmNews, wmNewsVO);
        if (wmUser != null) {
            wmNewsVO.setAuthorName(wmUser.getName());
        }
        ResponseResult result = ResponseResult.okResult(wmNewsVO);
        result.setHost(webSite);
        return result;
    }

    /**
     * @param status 2 审核失败 4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        if (status == null || dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            return ResponseResult.errorResult((AppHttpCodeEnum.DATA_NOT_EXIST));
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_ALLOW);
        }
        //修改文章状态
        LambdaUpdateWrapper<WmNews> wrapper =
                Wrappers.<WmNews>lambdaUpdate()
                        .set(WmNews::getStatus, status).eq(WmNews::getId, dto.getId());
//        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        this.update(wmNews,wrapper);
        //5. 通知定时发布文章
        // 发布时间
        long publishTime = wmNews.getPublishTime().getTime();
        // 当前时间
        long nowTime = new Date().getTime();
        long remainTime = publishTime - nowTime;
        // 发布文章
        rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                , wmNews.getId()
                , (message)->{                              // 延时消息 必设置
                    message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                    return message;
                }
        );
        log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        return ResponseResult.okResult();

    }

    //    @Override
//    public ResponseResult downOrUp(WmNewsDTO dto) {
//        //1.检查参数
//        if(dto == null || dto.getId() == null){
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
//        }
//        Short enable = dto.getEnable();
//        if(enable == null ||
//                (!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable))){
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
//        }
//        //2.查询文章
//        WmNews wmNews = getById(dto.getId());
//        if(wmNews == null){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
//        }
//        //3.判断文章是否发布
//        if(!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"当前文章不是发布状态，不能上下架");
//        }
//        //4.修改文章状态，同步到app端（后期做）TODO
//        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId())
//                .set(WmNews::getEnable,dto.getEnable()));
//        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
//    }
    @Override
    public ResponseResult findWmNewsById(Integer id) {
        //1 参数检查
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 执行查询
        WmNews wmNews = getById(id);
        if (wmNews == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3 返回结果
        ResponseResult result = ResponseResult.okResult(wmNews);
        result.setHost(webSite);
        return result;
    }

    @Override
    public ResponseResult searchList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage() - 1) * dto.getSize());
//        if (StringUtils.isNotBlank(dto.getTitle())) {
//            dto.setTitle("%" + dto.getTitle() + "%");
//        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(webSite);
        return result;
    }

    @Override
    @Transactional
    public ResponseResult submitNews(WmNewsDTO dto) {
        // 1 参数校验
        if (dto == null || StringUtils.isBlank(dto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //当type=-1时自动生成，暂时将type设置为null
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            wmNews.setType(null);//防止数据库报异常
        }
        //news的封面数据库存的是字符转换 而dto的封面存的是List集合
        if (CollectionUtils.isNotEmpty(dto.getImages())) {
            String imageStr = this.imagesToString(dto.getImages());//把集合转化为字符串
            wmNews.setImages(imageStr);
        }
        wmNews.setUserId(user.getId());
        //保存并修改
        this.saveOrUpdateWmNews(wmNews);
        //如果是草稿。不用保存关联关系
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNews.getStatus())) {
            return ResponseResult.okResult();
        }
        //3.1抽取文章内容中的应用图片的路径集合
        List<String> contentImages = this.parseContentImages(dto.getContent());
        //3.2保存内容和素材的关联关系
        if (CollectionUtils.isNotEmpty(contentImages)) {
            this.saveRelativeInfo(contentImages, wmNews.getId(), WemediaConstants.WM_CONTENT_REFERENCE);
        }
        //3.3保存封面和素材的关联关系
        this.saveRelativeInfoForCover(contentImages, wmNews, dto);
        //发送id
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE, wmNews.getId());
        log.info("消息发送队列内容{}" ,wmNews.getId());
        return ResponseResult.okResult();
    }

    private void saveRelativeInfoForCover(List<String> contentImages, WmNews wmNews, WmNewsDTO dto) {
        //拿到前端传递过来的封面集合
        List<String> images = dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())) {
            //需要自动生成封面
            if (contentImages.isEmpty()) {//如果没有内容封面，设置为无封面
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            } else if (contentImages.size() > 0 && contentImages.size() <= 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);//设置单图
                images = contentImages.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);//设置多图
                images = contentImages.stream().limit(3).collect(Collectors.toList());
            }
            if (CollectionUtils.isNotEmpty(images)) {
                wmNews.setImages(imagesToString(images));
            }
            updateById(wmNews);//更新wmNews中的图片类型及封面
        }
        if (CollectionUtils.isNotEmpty(images)) {
            //如果封面不是自动生成，那么获取的是前端传过来的封面集合，有前缀，需要替换
            images = images.stream().map(url -> url.replaceAll(webSite, "")).distinct().collect(Collectors.toList());
            saveRelativeInfo(images, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
        }

    }

    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
//        List<WmMaterial> wmMaterials = wmMaterialMapper.
//                selectList(Wrappers.<WmMaterial>lambdaQuery().eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())
//                        .in(WmMaterial::getUrl, urls));
//        List<Integer> collect = wmMaterials.stream().map(WmMaterial::getId).collect(Collectors.toList());
        //得到素材id数量
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        //判断素材id数量是否小于素材路径数量，小于则异常
        if (CollectionUtils.isEmpty(ids) || ids.size() < urls.size()) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "相关数据不存在");
        }
        //保持素材和文章关联关系
        wmNewsMaterialMapper.saveRelations(ids, newsId, type);
    }

    /**
     * todo有一定难度
     *
     * @param content
     * @return
     */
    private List<String> parseContentImages(String content) {
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        List<String> collect = maps.stream()
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))//找到type数据
                .map(o -> (String) o.get("value"))//得到每个type为image中的value值
                .map(url -> url.replace(webSite, ""))//替换前缀路径
                .distinct().collect(Collectors.toList());
        return collect;
    }

    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);//上架
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(WmThreadLocalUtils.getUser().getId());
        if (wmNews.getId() == null) {
            //保存
            this.save(wmNews);
        } else {//修改
            //删除文章和素材的关联关系
//            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
//            this.updateById(wmNews);
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imagesToString(List<String> images) {
        return images.stream().map(url -> url.replace(webSite, "")).
                collect(Collectors.joining(","));//收集，字符串拼接，用逗号隔开
    }
}
